#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/16 9:43
# @Author  : JY.Liu
# @Site    : http://github.com/lh1993
# @Mail    : lhln0119@163.com
# @File    : k8s.py
# @Software: PyCharm

from kubernetes import client, config
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(BASE_DIR, "config")
KUBE_FILE = os.path.join(CONFIG_DIR, "kubeconfig.yaml")

# 从kubeconfig.yaml加载k8s集群认证信息
config.kube_config.load_kube_config(config_file=KUBE_FILE)

# 获取API的CoreV1Api版本对象
CoreV1 = client.CoreV1Api()


def get_namespaced_pod(
        podname="None",
        deployment_name="None",
        namespace="jcss",
        deployment=False):
    """获取指定命名空间下指定POD的信息

    :param podname: pod名称
    :param deployment_name: deployment应用名称
    :param namespace: 命名空间
    :param deployment: 是否为deployment应用，默认为Flase
    :return: list
    """
    pod_ip = []
    if deployment is True:
        label = "app=%s" % deployment_name
        res = CoreV1.list_namespaced_pod(
            namespace=namespace, label_selector=label)
        for result in res.items:
            podname = result.metadata.name
            res = CoreV1.read_namespaced_pod(name=podname, namespace=namespace)
            pod_ip.append(res.status.pod_ip)
    else:
        res = CoreV1.read_namespaced_pod(name=podname, namespace=namespace)
        pod_ip.append(res.status.pod_ip)
    return pod_ip


if __name__ == "__main__":
    redis_ip = get_namespaced_pod(
        deployment_name="share-redis",
        namespace="jcss",
        deployment=True)
    print(redis_ip)
